﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace Synthetic.Security.TripleDES
{
    public class ErrorHandler
    {
        private string MESSAGE_TEMPLATE = "Simple File Encrypter Bug Report\nBug Report Submitted at: " + DateTime.Now.TimeOfDay + " on the " + DateTime.Now.Date + "\n" + "Report submitted by: " + Environment.UserName + "\n" + "Report Submitted from: [@IPADDRESS]" + "\n" + "Error Message: [@BUG]";
        private const string MESSAGE_TITLE = "SFE - Bug Report";
        private string smtp_PASSWORD;
        private string smtp_EMAIL;
        private List<string> Errors = new List<string>();

        public void Send()
        {
            PrepMessage();
            MailMessage message = new System.Net.Mail.MailMessage();
            message.To.Add("connor-harries@live.co.uk");
            message.Subject = MESSAGE_TITLE;
            message.From = new MailAddress("synthetic@leetcoders.org");
            message.Body = MESSAGE_TEMPLATE;
            SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
            smtp.Port = 587;

            //Confuse network snoopers
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] b = enc.GetBytes("");
            byte[] e = enc.GetBytes("");
            smtp_PASSWORD = enc.GetString(b);
            smtp_EMAIL = enc.GetString(e);
            //End confusion

            smtp.Credentials = new NetworkCredential(smtp_EMAIL, smtp_PASSWORD);
            smtp.EnableSsl = true;
            smtp.Send(message);
        }

        public int List()
        {
            return Errors.Count;
        }

        private void PrepMessage()
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                direction = stream.ReadToEnd();
            }
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);
            MESSAGE_TEMPLATE = MESSAGE_TEMPLATE.Replace("[@IPADDRESS]", direction);
            string data = "";
            foreach (string s in Errors)
            {
                data = data + "\n" + s;
            }
            MESSAGE_TEMPLATE = MESSAGE_TEMPLATE.Replace("[@BUG]", data);
        }

        public void AddBugToQueue(string bug)
        {
            Errors.Add(bug);
        }
    }
}
